<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class UserCode extends BaseModel
{
    //type
    const RETRIEVE_PASSWORD = 1;

    //expire
    const EXPIRE = 10; //minute

    protected $table = 'user_code';
    protected $fillable = ['email', 'code', 'type', 'expire', 'ip', 'is_used'];
    public $timestamps = true;


    protected $casts = [
        'is_used' => 'boolean'
    ];

    public function isUsed()
    {
        return $this->attributes['is_used'] == true;
    }

    public function isExpired()
    {
        return $this->attributes['expire'] < Carbon::now()->toDateTimeString();
    }

    public static function createCode($len = 4)
    {
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= rand(0, 9);
        }

        return $str;
    }

    public static function isFrequently($email)
    {
        /** @var Carbon $createdAt */
        $createdAt = UserCode::query()->where('email',$email)->orderBy('id','desc')->value('created_at');

        return isset($createdAt) && $createdAt->addMinute() > Carbon::now();
    }

    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub

        static::creating(function (UserCode $model) {
            DB::table('user_code')->where('email', $model->email)->update(['is_used' => true]);
            $model->expire = Carbon::now()->addMinutes(self::EXPIRE)->toDateTimeString();
        });
    }
}
